package com.execjar.utils;

/**
 * 计算工具类
 *
 * @author admin
 */
public class ArithmeticUtils {

    /**
     * 16进制累加(只保留2位)
     *
     * @param data
     * @return
     */
    public static String makeChecksum(String data) {
        data = data.replace(" ", "");
        if (data == null || data.equals("")) {
            return "";
        }
        int total = 0;
        int len = data.length();
        int num = 0;
        while (num < len) {
            String s = data.substring(num, num + 2);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }
        /**
         * 用256求余最大是255，即16进制的FF
         */
        int mod = total % 256;
        String hex = Integer.toHexString(mod);
        len = hex.length();
        // 如果不够校验位的长度，补0,这里用的是两位校验
        if (len < 2) {
            hex = "0" + hex;
        }
        return hex;
    }

    /*
     * 计算16进制补码
     */
    public static String calComplement(String hex) {
        Integer num = Integer.parseInt(hex, 16);//转成10进制
        String info = Integer.toBinaryString(num);
        num = ~num + 1;//补码
        String back = "";
        for (int j = info.length(); j >= 0; j--) {
            if (((1 << j) & num) != 0) {
                back = back + "1";
            } else {
                back = back + "0";
            }
        }
        back = conver2HexStr(back);
        return back;
    }

    public static String conver2HexStr(String str) {
        String sum = "";
        int t = str.length() % 4;
        if (t != 0) {
            for (int i = str.length(); i - 4 >= 0; i = i - 4) {
                String s = str.substring(i - 4, i);
                int tem = Integer.parseInt(String.valueOf(s), 2);
                sum = Integer.toHexString(tem).toUpperCase() + sum;
            }
            String st = str.substring(0, t);
            int tem = Integer.parseInt(String.valueOf(st), 2);
            sum = Integer.toHexString(tem).toUpperCase() + sum;
        } else {
            for (int i = str.length(); i - 4 >= -1; i = i - 4) {
                String s = str.substring(i - 4, i);
                int tem = Integer.parseInt(String.valueOf(s), 2);
                sum = Integer.toHexString(tem).toUpperCase() + sum;
            }
        }
        return sum;
    }

}
